#include "Channel.hpp"
class Listen : public Connection
{
public:
    Listen(uint16_t port, callback_t cb):_listen(std::make_shared<TcpSocket>())
    {
        _listen->BuildListenSocketMethod(port);
        _sockfd = _listen->SockFd();
        _cb = cb;
        SetNonBlock(_sockfd);
    }

    void Read() override
    {
        while (true)
        {
            struct sockaddr_in addr;
            socklen_t len = sizeof(addr);
            int fd = accept(_sockfd, (struct sockaddr *)&addr,&len);
            InetAddr peer(addr);
            if (fd >= 0)
            {
                // 通过owner,放入到hash中，并写入epoll中
                LOG(LogLevel::INFO) << "accept success";
                std::shared_ptr<Connection> channel = std::make_shared<Channel>(fd, _cb, peer);
                _owner->AddConnection(channel);
            }
            else 
            {
                if(errno == EAGAIN)
                {
                    break;//没有连接了，跳出循环
                }
                else if(errno == EINTR)
                    continue;
                else 
                {
                    LOG(LogLevel::ERROR) << "accept error";
                    Except();
                    break;
                }
            }
        }
    }

    void Write() override
    {}

    void Except() override
    {
        //出现异常
        _owner->DelConnection(_sockfd);
    }
    ~Listen() override
    {

    }

private:
    std::shared_ptr<Socket> _listen;
};